package com.cloud.job.job;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HtmlUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cloud.job.config.Config;
import com.cloud.job.model.entity.MFilm;
import com.cloud.job.model.entity.MFilmDetail;
import com.cloud.job.model.entity.MType;
import com.cloud.job.service.MFilmDetailService;
import com.cloud.job.service.MFilmService;
import com.cloud.job.service.MTypeService;
import com.cloud.job.util.DownloadUtil;
import com.cloud.job.util.HttpsUtil;
import com.cloud.job.util.OssHelper;
import com.xxl.job.core.context.XxlJobHelper;
import lombok.SneakyThrows;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.List;
import java.util.stream.Collectors;


@Component
public class FilmJob {


    String domain = "https://1080zyk5.com";
    private static boolean isLock = true;

    private static int maxPage = 543;
    @Autowired
    Config config;


    @Autowired
    OssHelper ossHelper;

    @Autowired
    MTypeService mTypeService;
    @Autowired
    MFilmService mFilmService;
    @Autowired
    MFilmDetailService mFilmDetailService;

    public void run() {
//        List<MType> listType = mTypeService.selectAll(null);
        for (int currentPage = maxPage; currentPage >= 1; currentPage--) {
            list(currentPage);
            XxlJobHelper.log("完成第：{}页", currentPage);
        }

    }

    /**
     * 循环分页信息
     */
    private void list(Integer currentPage) {
        String url = domain + "/?m=vod-index-pg-" + currentPage + ".html";

        String html = HttpsUtil.HttpRequest(url);
        if (StrUtil.isEmpty(html)) {
            return;
        }
        List<String> listUrl = ReUtil.findAllGroup1("<span class=\"xing_vb4\"><a href=\"(.*?)\" target=\"_blank\">", html);
        for (String detailUrl : listUrl) {
            if (StrUtil.isEmpty(detailUrl)) {
                return;
            }
            getListHtml(detailUrl);
        }
    }

    /**
     * 列表页
     */
    @SneakyThrows
    private void getListHtml(String source) {
        String url = domain + source;
        Connection connect = Jsoup.connect(url);
        Document document = connect.get();

        MFilm mFilm = new MFilm();

        mFilm.setImg(document.getElementsByClass("vodImg").select(".lazy").attr("src"));
        mFilm.setName(document.getElementsByClass("vodh").select("h2").text());
        mFilm.setUpdateInfomation(document.getElementsByClass("vodh").select("span").text());
        mFilm.setScore(Convert.toDouble(document.getElementsByClass("vodh").select("label").text()));


        String text = document.getElementsByClass("vodinfobox").select("li").html();


        mFilm.setOtherName(ReUtil.getGroup1("别名：<span>(.*?)</span>", text));
        mFilm.setDirector(ReUtil.getGroup1("导演：<span>(.*?)</span>", text));
        mFilm.setPerformer(ReUtil.getGroup1("主演：<span>(.*?)</span>", text));
        String twoName = ReUtil.getGroup1("类型：<span>(.*?)</span>", text);
        StrUtil.replace(twoName, "&nbsp;", " ");
        mFilm.setTwoTypeName(HtmlUtil.cleanHtmlTag(twoName));

        mFilm.setCountryName(ReUtil.getGroup1("地区：<span>(.*?)</span>", text));
        mFilm.setLanguageName(ReUtil.getGroup1("语言：<span>(.*?)</span>", text));
        mFilm.setReleaseTime(Convert.toInt(ReUtil.getGroup1("上映：<span>(.*?)</span>", text), 0));
        mFilm.setLongTime(Convert.toInt(ReUtil.getGroup1("片长：<span>(.*?)</span>", text), 0));
        mFilm.setTodayPlayCount(Convert.toInt(ReUtil.getGroup1("今日播放量：<span>(.*?)</span>", text), 0));
        mFilm.setSource(source);

        String html = document.html();
        String content = ReUtil.getGroup1("<!-- 开始 -->([\\s\\S]+?)<!--结束-->", html);
        content = StrUtil.replace(HtmlUtil.cleanHtmlTag(content), "剧情介绍：", "");
        content = StrUtil.replace(content, "\n", "");
        content = StrUtil.replace(content, " ", "");
        mFilm.setContent(content);

        //具体信息
        List<String> listZyk = document.getElementById("play_1").select("a").eachText();
        if (CollectionUtil.isNotEmpty(listZyk)) {
            listZyk = listZyk.stream().filter(t -> !t.equals("我要报错")).collect(Collectors.toList());
        }
        mFilm.setDetailCount(listZyk.size());
        MFilm filmResult = mFilmService.selectOne(new MFilm().setSource(source));
        Integer fid = 0;
        if (filmResult != null) {
            //如果存在则删除明细
            //先对比总数是否一至，如果是则跳出
            if (filmResult.getDetailCount().equals(mFilm.getDetailCount())) {
                return;
            }
            //更新
            mFilmService.updateById(mFilm);
            fid = filmResult.getId();
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("f_id", fid);
            mFilmDetailService.remove(queryWrapper);
        } else {
            mFilmService.save(mFilm);
            fid = mFilm.getId();
        }
        String zyk = CollectionUtil.join(listZyk, ",");

        String ZykyunStr = ReUtil.getGroup1("<h3>播放类型：zykyun</h3>([\\s\\S]+?)</ul>", html);
        List<String> listZykyun = ReUtil.findAllGroup1("value=\"(.*?)\"", ZykyunStr);
        String zykyun = CollectionUtil.join(listZykyun, ",");

        MFilmDetail mFilmDetail = new MFilmDetail();
        mFilmDetail.setFId(fid);
        mFilmDetail.setZyk(zyk);
        mFilmDetail.setZykyun(zykyun);
        mFilmDetailService.save(mFilmDetail);
    }

    /**
     * 替换内容页的图片
     */
    private String replaceContentImg(String content) {
        List<String> imgList = ReUtil.findAllGroup1("src=\"(.*?)\"", content);
        for (String itemImg : imgList) {
            content = content.replace(itemImg, upload("", itemImg));
            content = content.replace("//", "");
        }
        return content;
    }

    private String upload(String type, String url) {
        String path = url.replace(domain, "").replace("-lp", "");
        path = path.replace("/uploads", "uploads");
        String ossUploadPath = "";
        if (!StrUtil.isEmpty(type)) {
            ossUploadPath += type + "\\";
        }
        ossUploadPath += path.replace("/", "\\");
        path = config.getTempImgPath() + ossUploadPath;
        if (!url.contains("http") && !url.contains("https")) {
            url = domain + url;
        }
        try {
            String fileName = StrUtil.subAfter(path, "\\", true);
            if (StrUtil.isEmpty(fileName)) {
                return "";
            }
            String checkPath = path.replace(fileName, "");
            if (!FileUtil.exist(checkPath)) {
                FileUtil.mkdir(checkPath);
            }
            //下载到本地
            DownloadUtil.downloadFile(url, path);
            //上传到oss
            String ossPath = ossUploadPath.replace("\\", "/");
            ossPath = ossPath.replace("//", "/");
            ossHelper.uploadFileToOss(new File(path), ossPath);
            if (FileUtil.isFile(path)) {
                //删除本地文件
                FileUtil.del(new File(path));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return config.getImgUrl() + ossUploadPath.replace("\\", "/");
    }

}
